/* � 2009 ROBO Design
 * http://www.robodesign.ro
 */
        
// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
    
    function reInitGomme(){
        
        showOrHide = 0;
        $('#gommeActivee').val(showOrHide);
        $('#effacerBouton').removeClass();
        $('#effacerBouton').addClass('gomme');
         
    }
    var dessins;
      
    window.addEventListener('load', function () {
        var canvas, context, canvaso, contexto;
        var color, epaisseur;
        var isGommeActive = false;
        // The active tool instance.
        var tool;
        var tool_default = 'pencil';
       
                         
        function init () {
            // Find the canvas element.
            canvaso = document.getElementById('imageView');
            if (!canvaso) {
                alert('Error: I cannot find the canvas element!');
                return;
            }

            if (!canvaso.getContext) {
                alert('Error: no canvas.getContext!');
                return;
            }

            // Get the 2D canvas context.
            contexto = canvaso.getContext('2d');
            if (!contexto) {
                alert('Error: failed to getContext!');
                return;
            }

            // Add the temporary canvas.
            var container = canvaso.parentNode;
            canvas = document.createElement('canvas');
            if (!canvas) {
                alert('Error: I cannot create a new canvas element!');
                return;
            }

            canvas.id     = 'imageTemp';
            canvas.width  = canvaso.width;
            canvas.height = canvaso.height;
            container.appendChild(canvas);
                 
            context = canvas.getContext('2d');
            //Si on veut que les bords soient arrondis
            //context.lineJoin = 'round';
            //context.lineCap = 'round';
            
            //initialise le tableau qui contient l'ensemble des dessins du canvas
            dessins = new Array();          
                      
            // Get the tool select input.
            var tool_select = document.getElementById('dtool');
            if (!tool_select) {
                alert('Error: failed to get the dtool element!');
                return;
            }
            tool_select.addEventListener('change', ev_tool_change, false);

            // Activate the default tool.
            if (tools[tool_default]) {
                tool = new tools[tool_default]();
                tool_select.value = tool_default;
            }

            // Attach the mousedown, mousemove and mouseup event listeners.
            canvas.addEventListener('mousedown', ev_canvas, false);
            canvas.addEventListener('mousemove', ev_canvas, false);
            canvas.addEventListener('mouseup',   ev_canvas, false);
        }
       
        // The general-purpose event handler. This function just determines the mouse 
        // position relative to the canvas element.
        function ev_canvas (ev) {
            epaisseur = document.getElementById("epaisseur").value;
            if(isGommeActive == true){
                color = "ffffff" ;
            }
            else color = document.getElementById("couleur").value;	
            context.lineWidth = epaisseur;
            context.fillStyle= color;
            context.strokeStyle = color;
            	
            if (ev.layerX || ev.layerX == 0) { // Firefox
                ev._x = ev.layerX;
                ev._y = ev.layerY;
            } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            }

            // Call the event handler of the tool.
            var func = tool[ev.type];
            if (func) {
                func(ev);
            }
            
        }

        // The event handler for any changes made to the tool selector.
        function ev_tool_change (ev) {
            if (tools[this.value]) {
                tool = new tools[this.value]();
	  
            }
            reInitGomme();
        }
       
        
     
        // This function draws the #imageTemp canvas on top of #imageView, after which 
        // #imageTemp is cleared. This function is called each time when the user 
        // completes a drawing operation.
        function img_update () {
            contexto.drawImage(canvas, 0, 0);
            context.clearRect(0, 0, canvas.width, canvas.height);
        }

        // This object holds the implementation of each drawing tool.
        var tools = {};

        // Pencil
        tools.pencil = function () {
            var tool = this;
            this.started = false;
            $('#casePlein').slideUp();
            $('#tailleCoeur').slideUp();
            
             
          
            // This is called when you start holding down the mouse button.
            // This starts the pencil drawing.
            this.mousedown = function (ev) {
                isGommeActive = false;
                context.beginPath();
                context.moveTo(ev._x, ev._y);
                var objJSON = {
                    "type" : 'pencil', 
                    "x" : ev._x, 
                    "y" : ev._y, 
                    "size" : epaisseur, 
                    "color" : color, 
                    "mouse" : "down",
                    "qui" : "soi"
                };  
                dessins.push(objJSON);
                now.distributeForm(objJSON, false); 
                tool.started = true;
            };

            // This function is called every time you move the mouse. Obviously, it only 
            // draws if the tool.started state is set to true (when you are holding down 
            // the mouse button).
            this.mousemove = function (ev) {
                isGommeActive = false;
                if (tool.started) {         
                    context.lineTo(ev._x, ev._y);
                    var objJSON = {
                        "type" : 'pencil', 
                        "x" : ev._x, 
                        "y" : ev._y, 
                        "size" : epaisseur, 
                        "color" : color, 
                        "mouse" : "move",
                        "qui" : "soi"
                    }; 
                    dessins.push(objJSON);
                    now.distributeForm(objJSON); 
                    context.stroke();
                }
            };

            // This is called when you release the mouse button.
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    img_update();
                }
            };
        };
        

        // The rectangle tool.
        tools.rect = function () {
            var tool = this;
            this.started = false;
            $('#casePlein').slideDown();
            $('#tailleCoeur').slideUp();
            
            
            this.mousedown = function (ev) {
                isGommeActive = false;
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                
                isGommeActive = false;
                if (!tool.started) {
                    return;
                }
                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0),
                w = Math.abs(ev._x - tool.x0),
                h = Math.abs(ev._y - tool.y0);

                context.clearRect(0, 0, canvas.width, canvas.height);

                if (!w || !h) {
                    return;
                }
                if(document.getElementById("plein").checked==false){
                    context.strokeRect(x, y, w, h);
                }
                else{
                    context.fillRect(x, y, w, h);
                }
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    var objJSON = {
                        "type" : 'rect', 
                        "x" : Math.min(ev._x,  tool.x0), 
                        "y" : Math.min(ev._y,  tool.y0),
                        "w" : Math.abs(ev._x - tool.x0), 
                        "h" : Math.abs(ev._y - tool.y0),
                        "size" : epaisseur, 
                        "color" : color,
                        "plein" : document.getElementById("plein").checked ,
                        "qui" : "soi"
                      
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON, false); 
                    img_update();
                }
            };
        };
            
                
      
        
        
        // Smiley
        tools.smiley = function(){
            var tool = this;
            this.started = false;
            $('#tailleCoeur').slideUp();
            $('#casePlein').slideUp();
            
            
            this.mousedown = function(ev){
                isGommeActive = false;
                tool.started=true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
                
                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0);
                
                context.beginPath(); // Le cercle extérieur
                context.arc(x, y, 50, 0, Math.PI * 2); // Ici le calcul est simplifié
                context.stroke();

                context.beginPath(); // La boucle, un arc de cercle
                context.arc(x, y, 40, 0, Math.PI); // Ici aussi
                context.fill();

                context.beginPath(); // L'oeil gauche
                context.arc(x-20, y-5, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
                context.stroke();

                context.beginPath(); // L'oeil droit
                context.arc(x+20, y-5, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
                context.stroke();
            }
            
            this.mouseup = function (ev) {
                isGommeActive = false;
                if (tool.started) {
                    tool.started = false;
                    var objJSON = {
                        "type" : 'smiley', 
                        "x" : Math.min(ev._x,  tool.x0), 
                        "y" : Math.min(ev._y,  tool.y0),
                        "size" : epaisseur, 
                        "color" : color,
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON,false); 
                    img_update();
                }
            };
        };
        
        // Coeur
        tools.coeur = function(){
            var tool = this;
            this.started = false;
            $('#casePlein').slideUp();
            
             
            $('#tailleCoeur').slideDown();
            
            this.mousedown = function(ev){
                isGommeActive = false;
                tool.started=true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
                                          
                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0);
                w= document.getElementById("taille").value;
                                             
                context.beginPath();  
                context.arc(x, y, w, 90*(Math.PI/180), 0*(Math.PI/180), false);  
                context.stroke();  
                context.closePath();  
  
                context.beginPath();  
                context.arc(x, y+w*2, w, 270*(Math.PI/180), 0*(Math.PI/180), false);  
                context.stroke();  
                context.closePath();  
  
                context.beginPath();  
                context.arc(x+w*2, y, w, Math.PI, 90*(Math.PI/180), false);  
                context.stroke();  
                context.closePath();  
  
                context.beginPath();  
                context.arc(x+w*2, y+w*2, w, 180*(Math.PI/180), 270*(Math.PI/180), false);  
                context.stroke();  
                context.closePath(); 
            }
            
            this.mouseup = function (ev) {
                isGommeActive = false;
                if (tool.started) {
                    tool.started = false;
                    var objJSON = {
                        "type" : 'coeur', 
                        "x" : Math.min(ev._x,  tool.x0), 
                        "y" : Math.min(ev._y,  tool.y0),
                        "w" : document.getElementById("taille").value,
                        "size" : epaisseur, 
                        "color" : color,
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON, false); 
                    img_update();
                }
            };
        };
        
        
        //La gomme 
        tools.gommer = function () {
            var tool = this;	
            this.started = false;
            
            $('#tailleCoeur').slideUp();
            $('#casePlein').slideUp();
           
            this.mousedown = function (ev) {
                isGommeActive = true;
              
                context.beginPath();
                context.moveTo(ev._x, ev._y);
                var objJSON = {
                    "type" : 'gommer', 
                    "x" : ev._x, 
                    "y" : ev._y, 
                    "size" : epaisseur, 
                    "color" : color, 
                    "mouse" : "down",
                    "qui" : "soi"
                };  
                dessins.push(objJSON);
                now.distributeForm(objJSON, false); 
                tool.started = true;
            };

            // This function is called every time you move the mouse. Obviously, it only 
            // draws if the tool.started state is set to true (when you are holding down 
            // the mouse button).
            this.mousemove = function (ev) {
                isGommeActive = true;

                if (tool.started) {         
                    context.lineTo(ev._x, ev._y);
                    var objJSON = {
                        "type" : 'gommer', 
                        "x" : ev._x, 
                        "y" : ev._y, 
                        "size" : epaisseur, 
                        "color" : color, 
                        "mouse" : "move",
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON,false); 
                    context.stroke();
                }
            };

            // This is called when you release the mouse button.
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    img_update();
                }
            };
        };
        
        
          
        // Cercle
        tools.circle= function () {
            var tool = this;
            this.started = false;
            $('#casePlein').slideDown();
            $('#tailleCoeur').slideUp();
          
            
            this.mousedown = function (ev) {
                isGommeActive = false;
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                isGommeActive = false;
                if (!tool.started) {
                    return;
                }	 
                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0),
                w = Math.abs(ev._x - tool.x0),
                h = Math.abs(ev._y - tool.y0);
		  
                context.clearRect(0, 0, canvas.width, canvas.height);
	  
                //draw a circle
	
                context.beginPath();
                context.arc(x, y, w, h, Math.PI*2, true); 
                if(document.getElementById("plein").checked==true){
                    context.fill();
                }
                else{
                    context.stroke();
                }
                context.closePath();
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    // tool.mousemove(ev);
                    tool.started = false;
                    var objJSON = {
                        "type" : 'circle', 
                        "x" : Math.min(ev._x,  tool.x0), 
                        "y" : Math.min(ev._y,  tool.y0),
                        "w" : Math.abs(ev._x - tool.x0), 
                        "h" : Math.abs(ev._y - tool.y0), 
                        "size" : epaisseur, 
                        "color" : color,
                        "plein" : document.getElementById("plein").checked, 
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON, false); 
                    img_update();
                }
            };
        };
      
        //Ecrire du texte
        tools.ecrire= function(){
            var tool = this;
            this.started = false;
            isGommeActive = false;            
         
            $('#casePlein').slideUp();
            $('#tailleCoeur').slideUp();
            var txt;
            var police;
            /*var $dialog = $('<div id="dialog"></div>')
            .html('This dialog will show every time!')
            .dialog({
                autoOpen: false,
                title: 'Basic Dialog'
                
            });*/
            var $dialog = $('#dialogTexte')
            .dialog({
                autoOpen: true,
                title: 'Texte',
                closeOnEscape: true,
                draggable:true,
                width:200,
                show: {
                    effect: 'slide', 
                    direction: "up"
                }
            });
            $('#dialogTexte').show();
            this.mousedown = function (ev) {
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
                $dialog.dialog('open'); 
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }   
                txt = document.getElementById("ecrire-texte").value;
                police = document.getElementById("police").value;
                var tailleTexte = document.getElementById("tailleTexte").value;
                
                context.font = tailleTexte +"pt "+police;
                context.fillText(txt,tool.x0,tool.y0);
                              
            };           


            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    var objJSON = {
                        "type" : 'ecrire', 
                        "x0" : tool.x0, 
                        "y0" : tool.y0,                        
                        "font" : context.font, 
                        "color" : color,
                        "text" : txt,
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON,false);  
                    img_update();
                }
            }
        }

        // The line tool.
        tools.line = function () {
            var tool = this;
            this.started = false;
            $('#casePlein').slideUp();
            $('#tailleCoeur').slideUp();
        
            
            this.mousedown = function (ev) {
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }   
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.beginPath();
                context.moveTo(tool.x0, tool.y0);
                context.lineTo(ev._x,   ev._y);
                context.stroke();
                context.closePath();
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    var objJSON = {
                        "type" : 'line', 
                        "x0" : tool.x0, 
                        "y0" : tool.y0,
                        "x1" : ev._x, 
                        "y1" : ev._y, 
                        "size" : epaisseur, 
                        "color" : color,
                        "qui" : "soi"
                    };  
                    dessins.push(objJSON);
                    now.distributeForm(objJSON, false); 
                    img_update();
                }
            };
        };


        init();

    }, false);
}



 


$(document).ready(function(){
    canvas = document.getElementById('imageView');	
    context = canvas.getContext('2d');

    // Lorsqu'on reçoit un message on execute cette fonction
    now.receiveMessage = function(name, message){
        
        $("#messages").append("<br>" + name + ": " + message);
        document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
    }
	
    // Quand on clique sur le bouton send, on exécute cette fonction
    $("#send-form").submit(function(){
        now.distributeMessage($("#text-input").val());
        $("#text-input").val(""); //reset du champ input
        return false;
    });
    
             
    // Quand on clique sur le bouton effacer, on exécute cette fonction
    $("#erase").click(function(){
        if(confirm("Etes-vous sûr de vouloir tout effacer? Cela affectera tous les utilisateurs.")){
            context.clearRect(0, 0, canvas.width, canvas.height);
            dessins = new Array();
            var objJSON = {
                "type" : "effacer"
            };  
            now.distributeForm(objJSON,false);  
        }
    });
      
    $("#sauve").click(function(){
        window.open(canvas.toDataURL("image/png"));
    });
    $("#annuler").click(function(){ 
        //parcours des dessins pour annuler le dernier dessin que l'utilisateur courant a fait
        for (k=0; k<=dessins.length-1; k++){
            if(dessins[k].qui=='soi'){
                //j obtient la valeur du dernier dessin effectué par l'utilisateur
                var j=k;
            }
        }
        //
        //si le dernier objet est un dessin au crayon, 
        //supprimer l'ensemble du même trait de crayon
        if (dessins[j].type=='pencil'){
            while (dessins[j].type=='pencil' && j>0){
                dessins.splice(j,1);
                j--;
            }
        }
        else{
            // idem si c'est la gomme
            if (dessins[j].type=='gommer'){
                while(dessins[j].type =='gommer'  && j>0){                   
                    dessins.splice(j,1);
                    j--;
                }
            }
            else{
                // sinon supprimer j directement
                dessins.splice(j,1);
            }
        }
           
        // envoyer à tous qu'un élément a été supprimé
        context.clearRect(0, 0, canvas.width, canvas.height);
        var objJSON = {
            "type" : "annuler",
            "j" : j
        };  
        now.distributeForm(objJSON, false);
        
        //renvoyer tous les dessins
        for (i in dessins){
            now.distributeForm(dessins[i], true);
        }
   
    });      
        
 
    now.receiveForm = function(objJSON, tous){  
        context.lineWidth = objJSON.size;
        context.fillStyle = objJSON.color;
        context.strokeStyle = objJSON.color;
        
        if(tous == false){
            if (objJSON.type != "annuler"){
                //ajout des dessins des autres
                objJSON.qui='else';
                dessins.push(objJSON);
            }
        }
               			
        if(objJSON.type == "line"){ 			
            context.beginPath();			
            context.moveTo(objJSON.x0, objJSON.y0);
            context.lineTo(objJSON.x1, objJSON.y1);
            context.stroke();
            context.closePath();
            			
        }
        if(objJSON.type == "pencil"){
            if (objJSON.mouse == "down"){
                context.beginPath();
                context.moveTo(objJSON.x, objJSON.y);
            }
            if(objJSON.mouse == "move"){
                context.lineTo(objJSON.x, objJSON.y);
                context.stroke();
            }	
        }
        if(objJSON.type == "rect"){ 
            context.beginPath();
            context.rect(objJSON.x, objJSON.y, objJSON.w, objJSON.h);
            if(objJSON.plein==false){
                context.stroke();
            }else{
                context.fill();
            }
            context.closePath();
			
        }
        if(objJSON.type == "circle"){ 
            context.beginPath();
            context.arc(objJSON.x, objJSON.y, objJSON.w, objJSON.h, Math.PI*2, true); 
            if(objJSON.plein==false){
                context.stroke();
            }else{
                context.fill();
            }
            context.closePath();
        }
        if(objJSON.type=="coeur"){
            context.beginPath();  
            context.arc(objJSON.x, objJSON.y, objJSON.w, 90*(Math.PI/180), 0*(Math.PI/180), false);  
            context.stroke();  
            context.closePath();  
  
            context.beginPath();  
            context.arc(objJSON.x, objJSON.y+objJSON.w*2, objJSON.w, 270*(Math.PI/180), 0*(Math.PI/180), false);  
            context.stroke();  
            context.closePath();  
  
            context.beginPath();  
            context.arc(objJSON.x+objJSON.w*2, objJSON.y, objJSON.w, Math.PI, 90*(Math.PI/180), false);  
            context.stroke();  
            context.closePath();  
  
            context.beginPath();  
            context.arc(objJSON.x+objJSON.w*2, objJSON.y+objJSON.w*2, objJSON.w, 180*(Math.PI/180), 270*(Math.PI/180), false);  
            context.stroke();  
            context.closePath(); 
            
        }
        if (objJSON.type=="smiley"){
            context.beginPath(); // Le cercle extérieur
            context.arc(objJSON.x, objJSON.y, 50, 0, Math.PI * 2); 
            context.stroke();

            context.beginPath(); // La bouche, un arc de cercle
            context.arc(objJSON.x, objJSON.y, 40, 0, Math.PI);
            context.fill();

            context.beginPath(); // L'oeil gauche
            context.arc(objJSON.x-20, objJSON.y-5, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
            context.stroke();

            context.beginPath(); // L'oeil droit
            context.arc(objJSON.x+20, objJSON.y-5, 20, (Math.PI / 180) * 220, (Math.PI / 180) * 320);
            context.stroke();
        }
        if (objJSON.type == "gommer"){
            if (objJSON.mouse == "down"){
                context.beginPath();
                context.moveTo(objJSON.x, objJSON.y);
            }
            if(objJSON.mouse == "move"){
                context.lineTo(objJSON.x, objJSON.y);
                context.stroke();
            }
        }
        if(objJSON.type=="ecrire"){
            context.font=objJSON.font;
            context.fillText(objJSON.text,objJSON.x0,objJSON.y0);
        }
        
        if (objJSON.type == "effacer"){
            context.clearRect(0, 0, canvas.width, canvas.height);
            dessins = new Array();
        }
        if (objJSON.type == "annuler"){
            context.clearRect(0, 0, canvas.width, canvas.height);
            dessins.splice(objJSON.j, 1);
        }
        
    }
	
    // Poppe une fenêtre de dialogue et demande le nom
    // par défaut Anonyme + un numéro
    // gestion du nom si on ferme la pop up avec la croix
    $('#dialogTexte').hide();    
    $('#casePlein').hide();
    $('#tailleCoeur').hide();
    now.name = prompt("Bonjour, quel est votre nom ?", "Anonyme"+Math.floor(Math.random()*16));
    if (now.name == null || now.name=="")
    {
        now.name = "Anonyme"+Math.floor(Math.random()*16);
    }
       
    document.onselectstart = function(){
        return false;
    }
    $("#welcome").append('Bienvenue ' + now.name);
  

    // animation du texte Bienvenue.
    $("#welcome").textAnimation({ 
        mode:"jump",           
        altitude:10,              //jump altitude[integer]   
        bound :false,             //bound animation[boolean]  
        onStart:"mouseenter",     //event handler for start animation[Browse jQuery Events]  
        onFinish:"mouseleave",    //event handler for finish animation[Browse jQuery Events]  
        fixed:"bottom",           //which fixed top or bottom ["top","bottom"]  
        delay:80,                 //delay time for animation between characters[integer]   
        interval:0,               //interval time for between animation[integer]  
        duration:400,              //animation duration time[integer]  
        repeat:false 
    });
    

    /// Affichage du Readme
    jQuery(document).ready(function() {
        $("#readme_plus").hide();
        $("#readme_titre").click(function () {
            $("#readme_plus").toggle("normal");
            $(".versBas").toggleClass("versHaut");
        });
    });
    
   
   
});

